import router from './router'
import store from '@/store'
import { asyncRoutes } from '@/router/index'
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css' // A modern alternative to CSS resets
const whiteList = ['LoginPage', '404Page']
router.beforeEach(async(to, form, next) => {
  Nprogress.start()
  const token = store.getters.token
  if (token) next()
  if (!token && !whiteList.includes(to.name)) {
    next({ name: 'LoginPage' })
    Nprogress.done()
  } else {
    if (whiteList.includes(to.name)) {
      next()
    } else {
      if (!store.getters.userId) {
        const { roles } = await store.dispatch('user/getUserInfo')
        const filterRoutes = asyncRoutes.filter(item => {
          return roles.menus.find(e => '/' + e === item.path)
        })
        store.commit('user/setRoutes', filterRoutes)
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)
      } else {
        next()
        Nprogress.done()
      }
    }
  }
})
// 后置路由守卫
router.afterEach(() => {
  // 结束进度条
  Nprogress.done()
})
